package com.ssh.dao;

import java.util.List;

import javax.inject.Inject;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;

import com.ssh.exception.UserException;
import com.ssh.model.Pager;
import com.ssh.model.SystemContext;
import com.ssh.model.User;

@Repository("userDao")
public class UserDao implements IUserDao {

	private SessionFactory sessionFactory;

	@Inject
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	private Session getSession() {
		return sessionFactory.getCurrentSession();
	}

	@Override
	public void addUser(User user) {
		this.getSession().save(user);
		Logger.getLogger("dao").debug("dao:adding a user...");
	}

	@Override
	public void updateUser(User user) {
		this.getSession().update(user);
		Logger.getLogger("dao").debug("dao:updating a user...");
	}

	@Override
	public void deleteUser(int id) {
		User user = (User) this.getSession().get(User.class, id);
		if(user==null){
			throw new UserException("this user is not existed...");
		}
		this.getSession().delete(user);
		Logger.getLogger("dao").debug("dao:deleting a user by id...");
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<User> getUsers() {
		List<User> users = this.getSession().createQuery("from User").list();
		Logger.getLogger("dao").debug("dao:getting users...");
		return users;
	}

	@Override
	public User getUser(int id) {
		User user = (User) this.getSession().get(User.class, id);
		Logger.getLogger("dao").debug("dao:getting a user by id...");
		return user;
	}
	
	@Override
	public User getUser(String name) {
		User user = (User) this.getSession().createQuery("from User where name=?").setParameter(0, name).uniqueResult();
		Logger.getLogger("dao").debug("dao:getting a user...");
		return user;
	}

	@Override
	public User getUser(int id, String name) {
		User user = (User) this.getSession().createQuery("from User where name=? and id!=?").setParameter(0, name).setParameter(1, id).uniqueResult();
		Logger.getLogger("dao").debug("dao:getting a user...");
		return user;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pager<User> findUsers() {
		int size = SystemContext.getSize();
		int offset = SystemContext.getOffset();
//		System.out.println(offset+":"+size);
		Query query = this.getSession().createQuery("from User");
		query.setFirstResult(offset).setMaxResults(size);
		List<User> datas = query.list();
		Pager<User> users = new Pager<User>();
		users.setData(datas);
		users.setOffset(offset);
		users.setSize(size);
		long total = (Long)this.getSession().createQuery("select count(*) from User").uniqueResult();
		users.setTotal(total);
		Logger.getLogger("dao").debug("dao:getting pagers...");
		return users;
	}

}
